import axios from "axios";
import { splitFilename } from "./common";
import { resolveURL } from "./useRequest";
import { ElUploadRequestOptions } from "element-plus/es/components/upload/src/upload.type";

export function useCustomHttpPost(
	req: ElUploadRequestOptions,
	mediatype: string
) {
	return uploadChunks(req.file, mediatype);
}

async function uploadChunks(file: File, mediatype: string) {
	let start = 0;
	let uploadTimes = 0;
	const chunkSize = 1024 * 1024;
	const uid = file.lastModified;
	const { name, ext } = splitFilename(file.name);

	while (start <= file.size) {
		start = uploadTimes * chunkSize;
		const formdata = new FormData();
		const blob = file.slice(start, start + chunkSize);
		const blobName = `${name}.chunk-${uploadTimes}${ext}`;
		const blobFile = new File([blob], blobName);

		formdata.append("file", blobFile);
		formdata.append("uid", uid.toString());
		formdata.append("uploadTimes", uploadTimes.toString());

		const url = resolveURL("media/upload-chunks");

		await axios.post(url, formdata);
		uploadTimes++;
	}
	const url = resolveURL("media/merge-chunks");

	const formdata = new FormData();

	formdata.append("name", file.name);
	formdata.append("uid", uid.toString());
	formdata.append("mediatype", mediatype);
	const res = await axios.post(url, formdata);
	return res.data;
}
